<template>
  <div class="auth-modal">
    <div class="modal-overlay" @click="$emit('close')"></div>
    <div class="modal-content">
      <button class="close-button" @click="$emit('close')">
        <i class="icon-close">×</i>
      </button>
      
      <div class="auth-header">
        <h2>
          {{ 
            currentMode === 'login' ? '登录' : 
            currentMode === 'register' ? '注册' : 
            '重置密码' 
          }}
        </h2>
        <p v-if="currentMode === 'login'">
          还没有账号？<a href="#" @click.prevent="switchMode('register')">立即注册</a>
          <span class="divider">|</span>
          <a href="#" @click.prevent="switchMode('forgot')">忘记密码？</a>
        </p>
        <p v-else-if="currentMode === 'register'">
          已有账号？<a href="#" @click.prevent="switchMode('login')">立即登录</a>
        </p>
        <p v-else>
          想起密码了？<a href="#" @click.prevent="switchMode('login')">返回登录</a>
        </p>
      </div>
      
      <form @submit.prevent="handleSubmit">
        <!-- 登录表单 -->
        <template v-if="currentMode === 'login'">
          <div class="form-group">
            <label for="login-email">邮箱</label>
            <input
              id="login-email"
              type="email"
              v-model="loginForm.email"
              placeholder="请输入邮箱"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="login-password">密码</label>
            <input
              id="login-password"
              type="password"
              v-model="loginForm.password"
              placeholder="请输入密码"
              required
            />
          </div>
        </template>
        
        <!-- 注册表单 -->
        <template v-else-if="currentMode === 'register'">
          <div class="form-group">
            <label for="register-nickname">用户名</label>
            <input
              id="register-nickname"
              type="text"
              v-model="registerForm.nickname"
              placeholder="请输入用户名"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="register-email">邮箱</label>
            <input
              id="register-email"
              type="email"
              v-model="registerForm.email"
              placeholder="请输入邮箱"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="register-password">密码</label>
            <input
              id="register-password"
              type="password"
              v-model="registerForm.password"
              placeholder="请输入密码"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="register-confirm-password">确认密码</label>
            <input
              id="register-confirm-password"
              type="password"
              v-model="registerForm.confirmPassword"
              placeholder="请再次输入密码"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="register-captcha">验证码</label>
            <div class="captcha-row">
              <input
                id="register-captcha"
                type="text"
                v-model="registerForm.captcha"
                placeholder="请输入验证码"
                required
              />
              <button 
                type="button" 
                class="send-captcha" 
                @click="sendCaptcha('register')" 
                :disabled="isRegisterCaptchaCooldown"
              >
                {{ isRegisterCaptchaCooldown ? `${registerCaptchaCooldown}s后重试` : '获取验证码' }}
              </button>
            </div>
          </div>
          
          <div class="form-group">
            <Captcha v-model="registerForm.imageCaptcha" />
          </div>
        </template>
        
        <!-- 忘记密码表单 -->
        <template v-else>
          <div class="form-group">
            <label for="forgot-email">邮箱</label>
            <input
              id="forgot-email"
              type="email"
              v-model="forgotForm.email"
              placeholder="请输入注册时使用的邮箱"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="forgot-password">新密码</label>
            <input
              id="forgot-password"
              type="password"
              v-model="forgotForm.password"
              placeholder="请输入新密码"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="forgot-confirm-password">确认密码</label>
            <input
              id="forgot-confirm-password"
              type="password"
              v-model="forgotForm.confirmPassword"
              placeholder="请再次输入新密码"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="forgot-captcha">验证码</label>
            <div class="captcha-row">
              <input
                id="forgot-captcha"
                type="text"
                v-model="forgotForm.captcha"
                placeholder="请输入验证码"
                required
              />
              <button 
                type="button" 
                class="send-captcha" 
                @click="sendCaptcha('forgot')" 
                :disabled="isForgotCaptchaCooldown"
              >
                {{ isForgotCaptchaCooldown ? `${forgotCaptchaCooldown}s后重试` : '获取验证码' }}
              </button>
            </div>
          </div>
          
          <div class="form-group">
            <Captcha v-model="forgotForm.imageCaptcha" />
          </div>
        </template>
        
        <button type="submit" class="submit-button" :disabled="loading">
          {{ 
            currentMode === 'login' ? '登录' : 
            currentMode === 'register' ? '注册' : 
            '重置密码' 
          }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onBeforeUnmount } from 'vue';
import { useToast } from 'vue-toastification';
import { useUserStore } from '@/stores/user';
import Captcha from '@/components/common/Captcha.vue';
import { 
  sendEmailCaptcha as sendEmailCaptchaApi,
  resetPassword as resetPasswordApi 
} from '@/api/auth';

const toast = useToast();
const props = defineProps({
  mode: {
    type: String,
    default: 'login',
    validator: (value) => ['login', 'register', 'forgot'].includes(value)
  }
});

const emit = defineEmits(['close', 'switch-mode']);

const userStore = useUserStore();
const loading = ref(false);
const currentMode = ref(props.mode);

// 表单数据
const loginForm = ref({ email: '', password: '', remember: false });
const registerForm = ref({
  nickname: '',
  email: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  imageCaptcha: { captchaId: '', captchacode: '' }
});
const forgotForm = ref({ 
  email: '', 
  password: '', 
  confirmPassword: '', 
  captcha: '',
  imageCaptcha: { captchaId: '', captchacode: '' }  // 添加这一行
});

// 验证码倒计时
const registerCaptchaCooldown = ref(0);
const forgotCaptchaCooldown = ref(0);
const isRegisterCaptchaCooldown = computed(() => registerCaptchaCooldown.value > 0);
const isForgotCaptchaCooldown = computed(() => forgotCaptchaCooldown.value > 0);

const switchMode = (targetMode) => {
  currentMode.value = targetMode;
  emit('switch-mode', targetMode);
};

const sendCaptcha = async (type) => {
  const email = type === 'register' ? registerForm.value.email : forgotForm.value.email;
  if (!email) {
    toast.warning('请先输入邮箱');
    return;
  }
  
  try {
    await sendEmailCaptchaApi({
      email: email,  // 使用上面定义的email变量
      captchaId: type === 'register' 
        ? registerForm.value.imageCaptcha.captchaId 
        : forgotForm.value.imageCaptcha.captchaId,
      captchacode: type === 'register' 
        ? registerForm.value.imageCaptcha.captchacode 
        : forgotForm.value.imageCaptcha.captchacode,
    });
    toast.success('验证码已发送到您的邮箱');
    
    // 启动倒计时
    if (type === 'register') {
      registerCaptchaCooldown.value = 60;
      const interval = setInterval(() => {
        registerCaptchaCooldown.value--;
        if (registerCaptchaCooldown.value <= 0) clearInterval(interval);
      }, 1000);
    } else {
      forgotCaptchaCooldown.value = 60;
      const interval = setInterval(() => {
        forgotCaptchaCooldown.value--;
        if (forgotCaptchaCooldown.value <= 0) clearInterval(interval);
      }, 1000);
    }
  } catch (error) {
    toast.error(error.response?.data?.message || error.message || '发送验证码失败');
  }
};

const handleSubmit = async () => {
  loading.value = true;
  
  try {
    if (currentMode.value === 'login') {
      await userStore.login(loginForm.value);
      toast.success('登录成功');
      
      emit('close');
    } 
    else if (currentMode.value === 'register') {
      if (registerForm.value.password !== registerForm.value.confirmPassword) {
        throw new Error('两次输入的密码不一致');
      }
      
      await userStore.register({
        nickname: registerForm.value.nickname,
        email: registerForm.value.email,
        password: registerForm.value.password,
        confirmPassword: registerForm.value.confirmPassword,
        captchaId: registerForm.value.imageCaptcha.captchaId,
        captchacode: registerForm.value.imageCaptcha.captchacode,
        emailcode: registerForm.value.captcha
      });
      toast.success('注册成功');

      switchMode('login')
    }
    else {
      if (forgotForm.value.password !== forgotForm.value.confirmPassword) {
        throw new Error('两次输入的密码不一致');
      }
      
      // 直接调用API方法而不是通过store
      await resetPasswordApi({
        email: forgotForm.value.email,
        password: forgotForm.value.password,
        confirmPassword: forgotForm.value.confirmPassword,
        emailcode: forgotForm.value.captcha,
        captchaId: forgotForm.value.imageCaptcha.captchaId,  // 添加图形验证码ID
        captchacode: forgotForm.value.imageCaptcha.captchacode  // 添加图形验证码
      });
      toast.success('密码重置成功');
      switchMode('login');
    }
    
  } catch (error) {
    toast.error(error.response?.data?.message || error.message || '操作失败');
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
  .divider {
  margin: 0 8px;
  color: var(--text-tertiary);
  }
  .auth-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw; /* 使用视口单位确保覆盖整个屏幕 */
    height: 100vh;
    z-index: 2000;
  }
  
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw; /* 使用视口单位确保覆盖整个屏幕 */
    height: 100vh;
    background: rgba(0, 0, 0, 0.3);
    z-index: 2000;
  }
  
  .modal-content {
    position: fixed;
    top: 80%;
    left: 40%;
    transform: translate(-50%, -50%);
    z-index: 2001;
    background: var(--surface);
    border-radius: 12px;
    padding: 20px;
    width: 320px; /* 从380px改为320px */
    max-width: 90%;
    animation: modalFadeIn 0.3s ease forwards;
  }
  
  @keyframes modalFadeIn {
    from {
      opacity: 0;
      /* 移除 translateY */
    }
    to {
      opacity: 1;
    }
  }
  
  .close-button {
    position: absolute;
    top: 15px;
    right: 15px;
    width: 32px;
    height: 32px;
    background: rgba(0, 0, 0, 0.1);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    
    &:hover {
      background: rgba(0, 0, 0, 0.2);
    }
  
    .icon-close {
      font-size: 20px;
      color: var(--text-secondary);
      line-height: 1;
    }
  }
  
  .auth-header {
    text-align: center;
    margin-bottom: 5px;
    
    h2 {
      font-size: 1.5rem;
      margin-bottom: 10px;
      color: var(--text-primary);
    }
    
    p {
      color: var(--text-secondary);
      font-size: 0.9rem;
      
      a {
        color: $primary;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
  
  .form-group {
    margin-bottom: 15px;
    
    label {
      display: block;
      margin-bottom: 1px;
      font-size: 0.9rem;
      color: var(--text-primary);
      font-weight: 500;
    }
    
    input {
      width: 100%;
      padding: 2px 10px; /* 从12px 15px改为10px 12px */
      
      border: 1px solid rgba(var(--border-color-rgb), 0.3);
      border-radius: 6px;
      background: var(--surface);
      color: var(--text-primary);
      font-size: 0.95rem;
      transition: all 0.3s ease;
      
      &:focus {
        border-color: $primary;
        box-shadow: 0 0 0 2px rgba($primary, 0.2);
        outline: none;
      }
      
      &::placeholder {
        color: var(--text-tertiary);
      }
    }
  }
  
  .captcha-row {
    display: flex;
    gap: 10px;
    
    input {
      flex: 1;
    }
    
    .send-captcha {
      flex-shrink: 0;
      padding: 0 15px;
      background: $primary;
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        background: darken($primary, 10%);
      }
      
      &:disabled {
        background: #ccc;
        cursor: not-allowed;
      }
    }
  }
  
  .form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    font-size: 0.9rem;
  }
  
  .remember-me {
    display: flex;
    align-items: center;
    color: var(--text-secondary);
    cursor: pointer;
    
    input {
      margin-right: 8px;
    }
  }
  
  .forgot-password {
    color: var(--text-secondary);
    text-decoration: none;
    
    &:hover {
      color: $primary;
      text-decoration: underline;
    }
  }
  
  .submit-button {
    width: 100%;
    padding: 12px;
    background: $primary;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 1rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-top: 10px;
    
    &:hover {
      background: darken($primary, 10%);
    }
    
    &:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  }
  
  .loading-spinner {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 3px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 1s ease-in-out infinite;
  }
  
  /* 可以删除以下相关样式 */
  /*
  .social-login {
    margin-top: 25px;
  }
  
  .divider {
    display: flex;
    align-items: center;
    margin: 20px 0;
    color: var(--text-secondary);
    font-size: 0.9rem;
    
    &::before,
    &::after {
      content: "";
      flex: 1;
      height: 1px;
      background: rgba(var(--border-color-rgb), 0.3);
    }
    
    &::before {
      margin-right: 15px;
    }
    
    &::after {
      margin-left: 15px;
    }
  }
  
  .social-buttons {
    display: flex;
    justify-content: center;
    gap: 15px;
  }
  
  .social-button {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    transition: all 0.3s ease;
    
    &.wechat {
      background: #07C160;
      color: white;
    }
    
    &.github {
      background: #333;
      color: white;
    }
    
    &.google {
      background: #DB4437;
      color: white;
    }
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
  }
  */
  @keyframes modalFadeIn {
    from {
      opacity: 0;
      transform: translateY(-20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
  
  @media (max-width: 576px) {
    .modal-content {
      max-width: 90%;
      padding: 20px;
    }
  }
</style>